package com.slicktechnologies.server;

import static com.googlecode.objectify.ObjectifyService.ofy;

import java.util.List;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.slicktechnologies.shared.Quotation;
import com.slicktechnologies.shared.common.businessprocesslayer.Customer;

public class QuotationServiceImplentor extends RemoteServiceServlet
{

	/**
	 * 
	 */
	private static final long serialVersionUID = 8879665252154988914L;


	
	public void changeStatus(Quotation q) 
	{
		if(q!=null)
		{
			changeCustomerStatus(q);
		}
	}

	
    private void changeCustomerStatus(Quotation q)
    {
		
    	List<Customer>cust = null;
    	System.out.println("Called Customer Status Changed From Quotation");
    	System.out.println("Quotation Status Value "+q.getStatus());
    	
    	if(q.getCinfo()!=null)
    	{
    	   if(q.getStatus().equals(Quotation.APPROVED))
    	   {
    		  if(q.getCompanyId()!=null)
    		   cust =	ofy().load().type(Customer.class).filter("count",q.getCinfo().getCount()).
    				   filter("companyId",q.getCompanyId()).list();
    		  else
    			  cust =ofy().load().type(Customer.class).filter("count",q.getCinfo().getCount()).list(); 
    	      if(cust!=null)
    	      {
    	    	  System.out.println("Size is "+cust.size());
    	      for(Customer c:cust)
    	          {
    	    	  	if(!(c.getStatus().equals(Customer.CUSTOMERACTIVE)))
    	    	  	{
    	    	  		System.out.println("Changing Status of Customer --"+c.getName());
    	    	  		c.setStatus(Customer.CUSTOMERPROSPECT);
    	    	  		System.out.println("Changed Status To --"+c.getStatus());
    	    	  		
    	    	  	}
    				
    	    	  }	
    	      }
    	   }
    	   
    	   if(q.getStatus().equals(Quotation.QUOTATIONUNSUCESSFUL))
    	   {
    		   if(q.getCompanyId()!=null)
    		    cust =ofy().load().type(Customer.class).filter("count",q.getCinfo().getCount())
    		    		.filter("companyId",q.getCompanyId()).list();
    		   else
    			   cust =ofy().load().type(Customer.class).filter("count",q.getCinfo().getCount()).list();  
    		   
    	       if(cust!=null)
    	      for(Customer c:cust)
    	          {
    	    	  	if(!(c.getStatus().equals(Customer.CUSTOMERACTIVE)))
    	    	  	{
    	    	  		System.out.println("Changing Status of Customer --"+c.getName());
    	    	  		c.setStatus(Customer.CUSTOMERCREATED);
    	    	  		System.out.println("Changed Status To --"+c.getStatus());
    	    	  		
    	    	  	}
    				
    	    	  	 }
    	      }
    	   if(cust!=null&&cust.size()!=0)
    	       ofy().save().entities(cust).now();
    	} 
    	
    	ofy().save().entity(q).now();
    	
     }
	
}
